package com.example.victory.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class DataSourceConfig {
    /**
     * druid的过滤器设置
     */
    @Value("${spring.datasource.druid.filters:}")
    private String filters;

    @Primary
    @Bean("dbMysql")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSourceMysql() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        if (!StringUtils.isEmpty(filters)) {
            try {
                dataSource.setFilters(filters);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return dataSource;
    }

    @Bean("dbOracle")
    @ConfigurationProperties(prefix = "spring.ds-oracle")
    public DataSource dataSourceOracle() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        if (!StringUtils.isEmpty(filters)) {
            try {
                dataSource.setFilters(filters);
                dataSource.setValidationQuery("SELECT 1 FROM SYS.DUAL");
                dataSource.setTestOnBorrow(true);
                //dataSource.setTestOnReturn(true);
                dataSource.setTestWhileIdle(true);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return dataSource;
    }
}
